package controllers;

import helpers.ConfigManager;
import helpers.DocumentManager;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import entities.FileModel;

@WebServlet(name = "EditorServlet", urlPatterns = {"/EditorServlet"})
public class EditorServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

   /**
    * 处理get/post请求
    * @param request
    * @param response
    * @throws ServletException
    * @throws IOException
    */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        DocumentManager.Init(request, response);

        String fileName = request.getParameter("fileName");
        String fileExt = request.getParameter("fileExt");

        if (fileExt != null) {
            try {
                fileName = DocumentManager.CreateDemo(fileExt);
            } catch (Exception ex) {
                response.getWriter().write("Error: " + ex.getMessage());    
            }
        }

        FileModel file = new FileModel(fileName);
        if ("embedded".equals(request.getParameter("mode"))) {
            file.InitDesktop();
        }
        if ("view".equals(request.getParameter("mode"))) {
            file.editorConfig.mode = "view";
        }

        if (DocumentManager.TokenEnabled()) {
            file.BuildToken();
        }

        request.setAttribute("file", file);
        request.setAttribute("docserviceApiUrl", ConfigManager.GetProperty("files.docservice.url.api"));
        request.getRequestDispatcher("editor.jsp").forward(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Editor page";
    }
}
